package com.security.control.core.authentication.mobile;

import com.security.control.core.support.UUIDCreaterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.stereotype.Component;

/**
 * @author imoot@gamil.com
 * @date 2019/1/15 0015 9:32
 * 短信登录配置
 */
@Component
public class SmsValidateCodeAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler myAuthenticationFailureHandler;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        //初始化并配置短信验证码过滤器
        SmsValidateCodeAuthenticationFilter smsValidateCodeAuthenticationFilter = new SmsValidateCodeAuthenticationFilter();
        smsValidateCodeAuthenticationFilter.setAuthenticationManager(httpSecurity.getSharedObject(AuthenticationManager.class));
        smsValidateCodeAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        smsValidateCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
        //生成uuid
        String key = UUIDCreaterUtils.uuidCreat();
        //把生成的uuid作为键，用户信息作为值存储到cookie中，并把键值存储到数据中
        smsValidateCodeAuthenticationFilter.setRememberMeServices(new PersistentTokenBasedRememberMeServices(key,userDetailsService,persistentTokenRepository));

        //初始化并配置userDetailsService到短信验证码服务提供商中
        SmsValidateCodeAuthenticationProvider smsValidateCodeAuthenticationProvider = new SmsValidateCodeAuthenticationProvider();
        smsValidateCodeAuthenticationProvider.setUserDetailsService(userDetailsService);

        //把过滤器和服务提供商配置到http请求过滤链中
        httpSecurity.authenticationProvider(smsValidateCodeAuthenticationProvider)
                .addFilterAfter(smsValidateCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
